package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来了一个GET请求...");

        //1. 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");
        System.out.println("remember = " + remember);

        //2. 调用service
        UserService us = new UserService();
        User loginUser = us.login(username, password);

        //3. 判定返回的结果
        if(loginUser != null){

            //4. 作出响应: 如果成功就跳转到首页

            //4.0 判定有没有勾选 记住我 选项
            if(remember != null){ //如果勾选了，那么值就是： on , 没有勾选就是  null

                //4.0.1 把账号和密码放到cookie里面，给回浏览器
                Cookie usernameCookie = new Cookie("username",username);
                usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                resp.addCookie(usernameCookie);

                Cookie passwordCookie = new Cookie("password",password);
                passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                resp.addCookie(passwordCookie);
            }

            //4.1 跳转之前，先把用户对象，保存到作用域中
            req.getSession().setAttribute("user" ,loginUser);

            //4.2 跳转到首页
            resp.sendRedirect("index.jsp");

        }else{
            //5. 如果失败，还是跳转到登录页面，显示错误的信息

            //5.1 先把错误的信息保存到作用域
            req.getSession().setAttribute("msg" , "用户名或者密码错误！");

            //5.2 跳转到登录的页面
            resp.sendRedirect("login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来了一个POST请求...");
        this.doGet(req, resp);
    }
}
